package com.glodon.paas.account.security.spring.login;

import org.apache.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.glodon.paas.consts.StringConst;
import com.glodon.paas.util.HttpUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("accountLoginEntryPoint")
public class AccountLoginEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException arg2) throws IOException, ServletException {
    	
    	if(HttpUtils.isAjaxRequest(request)){
    		response.setStatus(HttpStatus.SC_UNAUTHORIZED);
    		response.getOutputStream().print(StringConst.LOGOUT);
    	}
    	else{
    		response.sendRedirect(request.getContextPath() + "/login");
    	}
    }

}
